package com.example.myapplication.function.musicmode

class MelodyRecognizer {
    private val pitchDetector = PitchDetector()
    private val pitchHistory = mutableListOf<Double>()
    private val noteHistory = mutableListOf<String>()
    
    // 识别参数
    companion object {
        private const val HISTORY_SIZE = 50
        private const val CONFIDENCE_THRESHOLD = 0.7
    }

    data class DetectedNote(
        val note: String,
        val frequency: Double,
        val confidence: Double,
        val duration: Long
    )

    data class RecognitionResult(
        val melody: List<DetectedNote>,
        val scale: String?,
        val tempo: Double,
        val confidence: Double
    )

    /**
     * 处理音频数据并检测音高
     */
    fun processAudioData(audioData: FloatArray): DetectedNote? {
        val frequency = pitchDetector.detectPitch(audioData) ?: return null
        val note = pitchDetector.frequencyToNote(frequency)
        val confidence = pitchDetector.calculateAccuracy(frequency, note)
        
        // 只返回置信度较高的检测结果
        return if (confidence > CONFIDENCE_THRESHOLD) {
            DetectedNote(note, frequency, confidence, System.currentTimeMillis())
        } else {
            null
        }
    }

    /**
     * 添加检测到的音符到历史记录
     */
    fun addDetectedNote(note: DetectedNote) {
        noteHistory.add(note.note)
        pitchHistory.add(note.frequency)
        
        // 保持历史记录大小
        if (noteHistory.size > HISTORY_SIZE) {
            noteHistory.removeAt(0)
            pitchHistory.removeAt(0)
        }
    }

    /**
     * 识别音阶
     */
    fun detectScale(): String? {
        if (noteHistory.size < 7) return null // 至少需要7个音符
        
        val noteCount = mutableMapOf<String, Int>()
        noteHistory.forEach { note ->
            noteCount[note] = noteCount.getOrDefault(note, 0) + 1
        }
        
        // 简单的音阶识别逻辑（可根据需要扩展）
        return when {
            isMajorScale(noteCount) -> "大调"
            isMinorScale(noteCount) -> "小调"
            isPentatonicScale(noteCount) -> "五声音阶"
            else -> null
        }
    }

    private fun isMajorScale(noteCount: Map<String, Int>): Boolean {
        // 简化的大调检测逻辑
        val majorNotes = listOf("C4", "D4", "E4", "F4", "G4", "A4", "B4")
        return majorNotes.count { noteCount.containsKey(it) } >= 5
    }

    private fun isMinorScale(noteCount: Map<String, Int>): Boolean {
        // 简化的小调检测逻辑
        val minorNotes = listOf("C4", "D4", "D#4", "F4", "G4", "G#4", "A#4")
        return minorNotes.count { noteCount.containsKey(it) } >= 5
    }

    private fun isPentatonicScale(noteCount: Map<String, Int>): Boolean {
        // 简化的五声音阶检测逻辑
        val pentatonicNotes = listOf("C4", "D4", "E4", "G4", "A4")
        return pentatonicNotes.count { noteCount.containsKey(it) } >= 4
    }

    /**
     * 获取完整的识别结果
     */
    fun getRecognitionResult(): RecognitionResult {
        val scale = detectScale()
        val tempo = calculateTempo()
        val overallConfidence = noteHistory.map { it.length.toDouble() }.average()
        
        return RecognitionResult(
            melody = emptyList(), // 实际应该从历史记录构建
            scale = scale,
            tempo = tempo,
            confidence = overallConfidence
        )
    }

    private fun calculateTempo(): Double {
        // 简化的节奏计算
        return 120.0 // 默认120 BPM
    }

    /**
     * 清空历史记录
     */
    fun clearHistory() {
        pitchHistory.clear()
        noteHistory.clear()
    }
}